package com.shxzz.easy12306.framework.starter.base;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * IoC 持有者，用于非 IoC 管理对象获取 Bean
 * @author shxzz
 * @create 2024-02-20-18:59
 */
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.CONTEXT = applicationContext;
    }

    /**
     * 根据类型获取 Bean
     */
    public static <T> T getBean(Class<T> requiredType) {
        return CONTEXT.getBean(requiredType);
    }

    /**
     * 根据名称获取 Bean
     */
    public static Object getBean(String name) {
        return CONTEXT.getBean(name);
    }

    /**
     * 根据名称和类型获取 Bean
     */
    public static <T> T getBean(String name, Class<T> requiredType) {
        return CONTEXT.getBean(name, requiredType);
    }

    /**
     * 获取指定类型的 Bean 集合
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> type) {
        return CONTEXT.getBeansOfType(type);
    }

    /**
     * 获取 IoC 容器
     */
    public static ApplicationContext getInstance() {
        return CONTEXT;
    }
}